/*
 * version date author 
 * ────────────────────────────────── 
 * 1.0  Dec 1, 2011 Neal Miao 
 * 
 * Copyright(c) 2011, by HTWater. All Rights Reserved.
 */
package com.gmail.nealnb.sf;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

import com.gmail.nealnb.sf.util.EncdecUtil;

/**
 * 
 * 
 * @author Neal Miao
 * @version
 * @since v 1.0
 * @Date Dec 1, 2011 8:53:52 AM
 * 
 * @see
 */
public class SMSBroadcastReceiver extends BroadcastReceiver {
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
	 * android.content.Intent)
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		Map<String, String> configMap = getConfigration(context);
		Bundle bundle = intent.getExtras();
		// condition filter
		boolean enable = "0".equals(configMap.get("enable")) ? false : true;
		String toPhoneNum = configMap.get("to");
		if (enable && toPhoneNum.length() > 0 && bundle != null) {
			Object[] pdus = (Object[]) bundle.get("pdus");
			SmsMessage[] message = new SmsMessage[pdus.length];
			for (int i = 0; i < pdus.length; i++) {
				message[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
			}
			String orgSender = "";
			String textBody = "";
			for (SmsMessage msg : message) {
				String content = msg.getDisplayMessageBody();//.getMessageBody();
				String sender = msg.getOriginatingAddress();
				orgSender = sender;
				textBody += content;
			}
			Date date = new Date(message[0].getTimestampMillis());
			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			String time = format.format(date);
			textBody += " [来自:" + getPeople(context, orgSender) + orgSender
					+ "时间:" + time + "]";
			if (!filterFromNo(configMap.get("from"), orgSender)) {
				String[] toNoArr = toPhoneNum.split("\\.");
				sendMessage(toNoArr, textBody);
			}
		}
	}

	/**
	 * 发送短信
	 * 
	 * @param toNoArr
	 * @param textBody
	 * @return void
	 * @since v 1.0
	 */
	private void sendMessage(String[] toNoArr, String textBody) {
		for (String toNo : toNoArr) {
			new Thread(new MessageSender(toNo, textBody)).start();
			System.out.println("send " + textBody + " to " + toNo);
		}
	}

	/**
	 * 短信发送线程
	 * 
	 * @author Neal Miao
	 * @version
	 * @since v 1.0
	 * @Date Dec 6, 2011 9:17:16 AM
	 * 
	 * @see
	 */
	class MessageSender implements Runnable {

		private String toNo;
		private String textBody;

		public MessageSender(String toNo, String textBody) {
			this.toNo = toNo;
			this.textBody = textBody;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {
			SmsManager manager = SmsManager.getDefault();
			// manager.sendTextMessage(toNo, null, textBody, null, null);
//			int textLen = textBody.length();
//			int loop = textLen / 60;
//			int needAppend = textLen % 60;
//			for (int i = 0; i < loop; i++) {
//				manager.sendTextMessage(toNo, null,
//						textBody.substring(i * 60, (i + 1) * 60), null, null);
//			}
//			if (needAppend > 0) {
//				manager.sendTextMessage(toNo, null,
//						textBody.substring(loop * 60), null, null);
//			}
			try {
				Thread.sleep(2000);
				ArrayList<String> msgs = manager.divideMessage(textBody);
				manager.sendMultipartTextMessage(toNo, null, msgs, null, null);
				System.out.println("thread send to:" + toNo);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 是否过滤不发送
	 * 
	 * @param filter
	 * @param fromNo
	 * @return boolean
	 * @since v 1.0
	 */
	private boolean filterFromNo(String filter, String fromNo) {
		String[] fromNoArr = filter.split("\\.");
		boolean result = false;
		for (String from : fromNoArr) {
			if (fromNo.equals(from)) {
				result = true;
				break;
			}
		}
		return result;
	}

	/**
	 * 获取配置信息
	 * 
	 * @param context
	 * @return Map<String,String>
	 * @since v 1.0
	 */
	private Map<String, String> getConfigration(Context context) {
		SharedPreferences settings = context.getSharedPreferences(
				"com.gmail.nealnb.sf", 0);
		Map<String, String> map = new HashMap<String, String>();
		map.put("from",
				EncdecUtil.decrypt("miao", settings.getString("from", "")));
		map.put("to", EncdecUtil.decrypt("miao", settings.getString("to", "")));
		map.put("enable", settings.getString("enable", "0"));
		return map;
	}

	/**
	 * 根据电话号码取得联系人姓名
	 * 
	 * @param context
	 * @param num
	 * @return String
	 * @since v 1.0
	 */
	private String getPeople(Context context, String num) {
		String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER };
		// 将自己添加到 msPeers 中
		Cursor cursor = context.getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
				projection, // Which columns to return.
				ContactsContract.CommonDataKinds.Phone.NUMBER + " = '" + num
						+ "'", // WHERE clause.
				null, // WHERE clause value substitution
				null); // Sort order.
		if (cursor == null) {
			return "";
		}
		String name = "";
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			// 取得联系人名字
			int nameFieldColumnIndex = cursor
					.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
			name = cursor.getString(nameFieldColumnIndex);
		}
		return name;
	}

	// public void onReceive(Context context, Intent intent) {
	// Map<String, String> configMap = getConfigration(context);
	// Bundle bundle = intent.getExtras();
	// // condition filter
	// boolean enable = "0".equals(configMap.get("enable")) ? false : true;
	// String toPhoneNum = configMap.get("to");
	// if (enable && toPhoneNum.length() > 0 && bundle != null) {
	// Object[] pdus = (Object[]) bundle.get("pdus");
	// SmsMessage[] message = new SmsMessage[pdus.length];
	// final String[] text = new String[pdus.length];
	// for (int i = 0; i < pdus.length; i++) {
	// message[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
	// }
	// int j = 0;
	// for (SmsMessage msg : message) {
	// String content = msg.getMessageBody();
	// String sender = msg.getOriginatingAddress();
	// Date date = new Date(msg.getTimestampMillis());
	// SimpleDateFormat format = new SimpleDateFormat(
	// "yyyy-MM-dd hh:mm:ss");
	// String time = format.format(date);
	// if (!filterFromNo(configMap.get("from"), sender)) {
	// String[] toNoArr = toPhoneNum.split("\\.");
	// if (j == pdus.length - 1) {
	// String appendStr = "\n(来自："
	// + getPeople(context, sender) + sender
	// + "\n时间：" + time + ")";
	// text[j] = content + appendStr;
	// if (text[j].length() > 75) { // 最后一段超出范围，再分割
	// System.out.println("send last part:"+content);
	// sendMessage(toNoArr, content);
	// text[j] = appendStr;
	// }
	// } else {
	// text[j] = content;
	// }
	// System.out.println("text["+j+"]:"+text[j]);
	// sendMessage(toNoArr, text[j]);
	// }
	// j++;
	// }
	// }
	// }
}
